package com.lujieni.consumer.filter;

import com.lujieni.consumer.context.ErpUserContext;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author
 * @Title: ErpUserFilter
 * @Description:
 * @date 2022/11/21 5:27 下午
 *
 * 即使404也会先走过滤器
 */
public class ErpUserFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String userCode = request.getHeader("userCode");
        if(!StringUtils.isEmpty(userCode)) { // 有userCode我们就放行,没有就滚蛋蛋不会到controller
            ErpUserContext.setUserCode(userCode);
            try {
                filterChain.doFilter(request, response); //执行业务代码可能会异常导致没有remove所以要finally
            } finally {
                ErpUserContext.remove();
            }
        }else{
            response.sendRedirect("https://www.baidu.com"); // 重定向到百度,浏览器地址会改变
        }
    }

}
